<template>
  <div class="exam-manage">
    <!-- 操作栏 -->
    <el-card class="action-card">
      <template #header>
        <div class="card-header">
          <span>考试管理</span>
          <el-button type="primary" @click="handleAdd">创建考试</el-button>
        </div>
      </template>

      <!-- 搜索栏 -->
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="考试名称">
          <el-input v-model="searchForm.title" placeholder="请输入考试名称" clearable />
        </el-form-item>
        <el-form-item label="考试状态">
          <el-select v-model="searchForm.status" placeholder="请选择状态" clearable>
            <el-option label="未开始" value="NOT_STARTED" />
            <el-option label="进行中" value="IN_PROGRESS" />
            <el-option label="已结束" value="ENDED" />
          </el-select>
        </el-form-item>
        <el-form-item label="考试时间">
          <el-date-picker
            v-model="searchForm.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>

      <!-- 考试列表 -->
      <el-table :data="examList" border style="width: 100%">
        <el-table-column prop="examId" label="ID" width="60" />
        <el-table-column prop="title" label="考试名称" min-width="150" show-overflow-tooltip />
        <el-table-column label="考试时间" width="240">
          <template #default="{ row }">
            {{ row.startTime }} 至 {{ row.endTime }}
          </template>
        </el-table-column>
        <el-table-column prop="duration" label="时长" width="70">
          <template #default="{ row }">
            {{ row.duration }}分钟
          </template>
        </el-table-column>
        <el-table-column prop="totalPoints" label="总分" width="60">
          <template #default="{ row }">
            {{ row.totalPoints }}分
          </template>
        </el-table-column>
        <el-table-column prop="passScore" label="及格" width="60">
          <template #default="{ row }">
            {{ row.passScore }}分
          </template>
        </el-table-column>
        <el-table-column label="状态" width="80">
          <template #default="{ row }">
            <el-tag :type="getStatusType(row.status)" size="small">
              {{ getStatusText(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="防作弊" width="80">
          <template #default="{ row }">
            <el-tag :type="getAntiCheatingType(row.antiCheatingLevel)" size="small">
              {{ getAntiCheatingText(row.antiCheatingLevel) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button-group>
              <el-button type="primary" link size="small" @click="handleEdit(row)">编辑</el-button>
              <el-button type="primary" link size="small" @click="handleDetail(row)">详情</el-button>
              <el-button
                v-if="row.status === 'IN_PROGRESS'"
                type="success"
                link
                size="small"
                @click="handleMonitor(row)"
              >
                监控
              </el-button>
              <el-button type="danger" link size="small" @click="handleDelete(row)">删除</el-button>
              <el-button type="primary" link size="small" @click="handleSetQuestions(row)">题目设置</el-button>
            </el-button-group>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
// Remove axios import
// import axios from 'axios'

// Import API functions
import { getExams, deleteExam } from '@/api/exam'

const router = useRouter()

// 搜索表单
const searchForm = reactive({
  title: '',
  status: '',
  dateRange: []
})

// 分页数据
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(100)

// 考试列表数据
const examList = ref<any[]>([])

// 获取状态类型
const getStatusType = (status: string) => {
  const map: Record<string, string> = {
    0: 'info',
    1: 'success',
    2: 'warning'
  }
  return map[status] || 'info'
}

// 获取状态文本
const getStatusText = (status: string) => {
  const map: Record<string, string> = {
    0: '未开始',
    1: '进行中',
    2: '已结束'
  }
  return map[status] || '未知'
}

// 获取防作弊级别类型
const getAntiCheatingType = (level: number) => {
  const map: Record<number, string> = {
    0: 'info',
    1: 'success',
    2: 'warning',
    3: 'danger'
  }
  return map[level] || 'info'
}

// 获取防作弊级别文本
const getAntiCheatingText = (level: number) => {
  const map: Record<number, string> = {
    0: '无',
    1: '低',
    2: '中',
    3: '高'
  }
  return map[level] || '未知'
}

// 搜索
const handleSearch = async () => {
  try {
    const params = {
      page: currentPage.value,
      pageSize: pageSize.value,
      title: searchForm.title,
      status: searchForm.status,
      startDate: searchForm.dateRange[0],
      endDate: searchForm.dateRange[1]
    }
    // Replace axios call with API function call
    const response = await getExams(params)
    examList.value = response.data.records
    total.value = response.data.total
  } catch (error) {
    console.error('获取考试列表失败:', error)
    ElMessage.error('获取考试列表失败')
  }
}

// 重置
const handleReset = () => {
  searchForm.title = ''
  searchForm.status = ''
  searchForm.dateRange = []
  handleSearch()
}

// 创建考试
const handleAdd = () => {
  router.push('/main/exam/add')
}

// 编辑考试
const handleEdit = (row: any) => {
  console.log('编辑考试', row)
  router.push(`/main/exam/edit/${row.examId}`)
}

// 查看详情
const handleDetail = (row: any) => {
  router.push(`/main/exam/detail/${row.examId}`)
}

// 监控考试
const handleMonitor = (row: any) => {
  router.push(`/main/exam/monitor/${row.examId}`)
}

// 删除考试
const handleDelete = (row: any) => {
  ElMessageBox.confirm(
    '确定要删除该考试吗？删除后无法恢复。',
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    try {
      // Replace axios call with API function call
      await deleteExam(row.examId)
      ElMessage.success('删除成功')
      handleSearch()
    } catch (error) {
      console.error('删除考试失败:', error)
      ElMessage.error('删除考试失败')
    }
  }).catch(() => {
    // 取消删除
  })
}

// 题目设置
const handleSetQuestions = (row: any) => {
  router.push(`/main/exam/questions/${row.examId}`)
}

// 分页大小改变
const handleSizeChange = (val: number) => {
  pageSize.value = val
  handleSearch()
}

// 当前页改变
const handleCurrentChange = (val: number) => {
  currentPage.value = val
  handleSearch()
}

// 在 onMounted 中调用 handleSearch
onMounted(() => {
  handleSearch()
})
</script>

<style scoped>
.exam-manage {
  padding: 20px;
  height: 100%;
  display: flex;
  flex-direction: column;
  box-sizing: border-box;
  overflow: hidden;
}

.action-card {
  flex: 1;
  min-height: 0;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  flex-shrink: 0;
}

.search-form {
  margin-bottom: 20px;
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
  flex-shrink: 0;
}

:deep(.el-card__body) {
  height: 100%;
  display: flex;
  flex-direction: column;
  overflow: hidden;
  padding: 10px;
}

:deep(.el-table) {
  flex: 1;
  overflow: auto;
}

:deep(.el-table__body-wrapper) {
  overflow-y: auto;
}

:deep(.el-table .cell) {
  padding-left: 8px;
  padding-right: 8px;
}

:deep(.el-button-group .el-button--small) {
  padding: 4px 8px;
}

.pagination {
  margin-top: 10px;
  display: flex;
  justify-content: flex-end;
  flex-shrink: 0;
}

:deep(.el-select),
:deep(.el-form-item__content) {
  min-width: 200px;
}
:deep(.el-select-dropdown) {
  min-width: 220px !important;
}
:deep(.el-select-dropdown__item) {
  white-space: normal;
  word-break: break-all;
  min-width: 200px;
}
</style>
